import AppConstants from "../AppConstants"
import AppUtil from "../AppUtil"


/**
 * @description 层级管理器
 * @author mirahs
 * @email 2892727493@qq.com
 */
export default class LayerMgr {
    private static viewGroup: string

    // 层级及对应节点
    private static _layerMap: Map<number, cc.Node> = new Map()

    private static _zIndex: number = 0


    // 初始化层级
    public static init(viewGroup: string) {
        this.viewGroup = viewGroup

        // 框架初始化和切换场景后都会调用, 所以要清除之前的数据
        this._layerMap.clear()

        for (const name in AppConstants.viewLayer) {
            const value = AppConstants.viewLayer[name] as number
            this.newLayer(name, value)
        }
    }

    /**
     * 创建新层级
     * @param name 层级名称
     * @param value 层级 zIndex
     * @returns
     */
    public static newLayer(name: string, value: number) {
        let layer = cc.Canvas.instance.node.getChildByName(name)
        if (layer) return

        layer = new cc.Node(name)
        layer.parent = cc.Canvas.instance.node
        layer.group = this.viewGroup
        layer.zIndex = value

        // 挂载 Widget 组件, 保持跟 Canvas 一样大小
        AppUtil.setWidget(layer)

        this._layerMap.set(value, layer)
    }

    /**
     * 为节点设置层级父节点并把节点显示在最上层
     * @param node 节点
     * @param layer 层级
     */
    public static setLayer(node: cc.Node, layer: number) {
        const layerNode = this._layerMap.get(layer)
        if (!layerNode) {
            console.error(`LayerMgr.setLayer layer[${layer}] 不存在`)
            return
        }

        if (!node.parent) {
            node.parent = layerNode
        }

        node.zIndex = this._zIndex++
    }
}
